import path from "path";
import chalk from "chalk";
import fs from "fs";
import { RFile, GetJson, PathChoose, AskQuestions, AskOutPut } from "../util.js";
import F2S from "./F2S.js";

/**
 * 输出文件
 *
 * @param {String} filePath
 * @param {String} content
 */
const WriteFile = (filePath, content) => {
    fs.writeFile(path.resolve(filePath), content, "utf8", function (err) {
        if (err) {
            console.log(chalk.red(err));
        } else {
            console.log(chalk.greenBright(filePath + " : 输出成功!"));
        }
    });
};

/**
 * 导出文件
 *
 * @param {*} options
 * @param {*} config
 * @param {*} TypeStr
 * @param {*} ignore
 */
const ExportsFile = async (File, FileName, config, OutPut) => {
    WriteFile(OutPut + "/" + FileName + ".js", F2S(File, config, FileName));
};

export const Run = async (config) => {
    let DocPath = await PathChoose(config.path);
    const Doclist = await GetJson(DocPath._index);
    var QuestionsList = [];
    Doclist.forEach((ele) => {
        QuestionsList.push(ele.name + "(" + chalk.yellow(ele.key) + ")");
    });
    const answers = await AskQuestions(QuestionsList);
    if (answers._index == 0) {
        var requestList = [];
        Doclist.forEach((ele) => {
            requestList.push(RFile(ele.url));
        });
        var allDoc = await Promise.all(requestList);
        allDoc.forEach((ele, index) => {
            // console.log(Doclist[index].key);
            ExportsFile(ele, Doclist[index].key, config, config.apiPath);
        });
    } else {
        var selectDoc = Doclist[answers._index - 1];
        var wrihteDoc = await RFile(selectDoc.url);
        ExportsFile(wrihteDoc, selectDoc.key, config, config.apiPath);
    }
};
